<template>
	<PageWrapper>
		<!-- 页面容器，设置全屏高度和背景色 -->
		<view style="height: 100vh; background-color: #f5f5f5">
			<!-- 顶部Logo组件 -->
			<topLogo></topLogo>
			<!-- 主内容区域，设置内边距 -->
			<view style="padding: 20px;box-sizing: border-box;">
				<!-- 内容卡片容器，设置高度、背景色、圆角和内边距 -->
				<view
					style="height: 94vh; background-color: #fff; border-radius: 8px;box-sizing: border-box; padding: 20px">

					<!-- 顶部导航栏，包含学生姓名和返回按钮 -->
					<view
						style="box-sizing: border-box; display: flex; align-items: center;justify-content: space-between; padding-bottom: 20px; border-bottom: 1px solid #f5f5f5">
						<span>学生姓名：{{ name }}</span>
						<view @click="back"
							style="display: flex;align-items: center; border-radius: 3px;box-sizing: border-box; padding: 8px 20px; background-color: #0052d9">
							<text
								style="font-size: 18px;padding-top: 3px;box-sizing: border-box; color: #fff; margin-right: 9px">返回</text>
							<image src="/static/back.png" style=" width: 18px;height: 18px;" mode="">
							</image>
						</view>
					</view>
					<view
						style="height: 95%;padding-bottom: 15px;box-sizing: border-box; display: flex; flex-direction: column; justify-content: space-between">
						<view style=" display: flex; flex-direction: column; justify-content: space-between">
							<view class="container">
								<!-- 1. 全选选项 -->
								<view class="item" @click="handleAllClick">
									<checkbox foreColor="#fff" activeBackgroundColor="#0351D8" :checked="allChecked"
										@click="handleAllClick" />
									<text class="label" :class="{ checked: allChecked }">全选</text>
								</view>

								<!-- 2. 课程列表（使用checkbox-group统一管理） -->
								<checkbox-group @change="handleCourseChange">
									<view class="item" v-for="(course, index) in courses" :key="index">
										<checkbox foreColor="#fff" activeBackgroundColor="#0351D8"
											:value="index.toString()" :checked="course.selected" />
										<text @click="selectCourse(course)" class="label"
											:class="{ checked: course.selected }">
											<text style="margin-right: 24px">{{ course.subjectName }}</text>
											<text style="margin-right: 36px">{{ course.starTime }}
												-{{ course.endTime }}</text>
											<text>{{ course.tName }}</text>
										</text>
									</view>
								</checkbox-group>
							</view>
						</view>
						<view class="">
							<view @click="enterNumber"
								style="display: flex; justify-content: center; align-items: center; width: 100%; height: 66px; background: #0052d9; border-radius: 3px">
								<text style="font-weight: 600; font-size: 24px; color: #ffffff; line-height: 22px">消课
									({{ selectedCourseIds.length }})</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<up-modal v-model:show="showEnterNum" :show-confirm-button="false" title="输入学管工号" @cancel="cancel"
				width="660px">
				<view style=" width: 100%;box-sizing: border-box; padding: 30px 0px 0; border-top: 1px solid #E8E8E8 ;">
					<view style="margin-bottom: 30px">
						<text style="font-size: 20px; color: #333333">学管姓名：{{ manageName }}</text>
					</view>
					<view style="margin-bottom: 50px; display: flex; align-items: center">
						<text style="font-size: 20px; color: #333333">学管工号：</text>
						<up-input :customStyle="{height:'40px'}" fontSize='20px' placeholder="请输入学管工号" type="number"
							border="surround" v-model="managerCode"></up-input>
					</view>
					<view
						style="padding-bottom: 30px;box-sizing: border-box; display: flex;width: 100%;justify-content: center;">
						<view @click="cancel"
							style="margin-right: 15px; display: flex;justify-content: center;align-items: center; width: 132px;height: 48px;background: #E1E1E1;border-radius: 8px 8px 8px 8px;">
							<text style="font-weight: 600;font-size: 20px;color: #6B6B6B;">返回</text>
						</view>
						<view @click="callBackModal" style="display: flex;justify-content: center;align-items: center; width: 132px;
					height: 48px;
					background: #0052D9;
					border-radius: 8px 8px 8px 8px;">
							<text style="font-weight: 600;
					font-size: 20px;
					color: #fff;">确定</text>
						</view>
					</view>
				</view>
			</up-modal>
			<up-modal v-model:show="showRes" title="消课结果" width="660px" :show-confirm-button="false">
				<view style="width: 100%; padding: 20px 30px 0; border-top: 1px solid #e8e8e8">
					<view v-show="xiaokeList?.successList?.length>0" class="">

						<view style="margin-bottom: 18px">
							<text style="font-size: 20px; color: #333333">消课成功：</text>
						</view>
						<view style="margin-bottom: 50px">
							<view style="display: flex; align-items: center;margin-bottom: 18px;"
								v-for="(item, index) in xiaokeList.successList" :key="index">
								<up-icon name="checkmark-circle-fill" color="#65B85D" size="18"></up-icon>
								<text style="margin-right: 12px; margin-left: 14px">{{item.subjectName}}</text>
								<text style="margin-right: 12px">{{item.startTime}} - {{item.endTime}}</text>
								<text>{{item.tname}}老师</text>
							</view>
						</view>
					</view>
					<view v-show="xiaokeList?.failList?.length>0" class="">
						<view style="margin-bottom: 18px">
							<text style="font-size: 20px; color: #333333">消课失败：</text>
						</view>
						<view style="margin-bottom: 30px">
							<view style="margin-bottom: 18px" v-for="(item, index) in xiaokeList.failList" :key="index">
								<view style="margin-bottom: 10px; display: flex; align-items: center">
									<up-icon name="close-circle-fill" color="#E84335" size="18"></up-icon>
									<text style="margin-right: 12px; margin-left: 14px">{{item.subjectName}}</text>
									<text style="margin-right: 12px">{{item.startTime}} - {{item.endTime}}</text>
									<text>{{item.tname}}老师</text>
								</view>
								<view
									style="display: flex; align-items: center; padding: 12px 10px; box-sizing: border-box; width: 100%; background-color: #f3f3f3">
									<text style="font-size: 16px; color: #8e8e8e; line-height: 24px">
										失败原因：{{item.failReason}}
									</text>
								</view>
							</view>
						</view>
					</view>
					<view style="padding-bottom: 30px; display: flex;width: 100%;justify-content: center;">

						<view @click="toIndex" style="display: flex;justify-content: center;align-items: center; width: 132px;
					height: 48px;
					background: #0052D9;
					border-radius: 8px 8px 8px 8px;">
							<text style="font-weight: 600;
					font-size: 20px;
					color: #fff;">返回首页</text>
						</view>
					</view>
				</view>
			</up-modal>
			<up-modal v-model:show="takePhoto" :showConfirmButton="false" title="提示" width="660px">

				<view
					style="width: 100%; padding: 20px 0 0; border-top: 1px solid #e8e8e8;display: flex;flex-direction: column;">
					<view style="margin-bottom: 20px; text-align: center">
						<text style="font-size: 20px; color: #333333">录入头像注意事项！</text>
					</view>
					<view
						style="margin-bottom: 30px; display: flex; flex-direction: column; font-size: 20px; color: #333333">
						<text style="margin-bottom: 20px">人脸识别规则：</text>
						<text style="margin-bottom: 20px">1.正面免冠​：学生正对镜头，双眼平视，露出完整面部（额头、眉毛、耳朵清晰可见）。</text>
						<text style="margin-bottom: 20px">2.自然状态​：不化浓妆，不戴饰品/眼镜，头发不遮眉，避免美颜滤镜。</text>
						<text style="margin-bottom: 20px">3.光线背景​：光线均匀（避免强光或昏暗），纯色简洁背景（如白墙）。</text>
						<text style="margin-bottom: 20px">4.照片通途：学生到校签到核销课程。</text>
					</view>
					<view style="padding-bottom: 30px; display: flex;width: 100%;justify-content: center;">
						<view @click="Tipcancel"
							style="margin-right: 15px; display: flex;justify-content: center;align-items: center; width: 132px;height: 48px;background: #E1E1E1;border-radius: 8px 8px 8px 8px;">
							<text style="font-weight: 600;font-size: 20px;color: #6B6B6B;">返回</text>
						</view>
						<view @click="toTakePhoto" style="display: flex;justify-content: center;align-items: center; width: 132px;
					height: 48px;
					background: #0052D9;
					border-radius: 8px 8px 8px 8px;">
							<text style="font-weight: 600;
					font-size: 20px;
					color: #fff;">拍照录入</text>
						</view>
					</view>
				</view>
			</up-modal>
			<FullscreenSwiper />
		</view>
	</PageWrapper>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		ref,
		computed,
		reactive,
		onMounted,
		watch,
		onUnmounted
	} from 'vue';
	import topLogo from '@/components/topLogo.vue';
	import {
		getStudentCourseList,
		checkManager
	} from '@/api/getData.js'
	import FullscreenSwiper from "@/components/FullscreenSwiper.vue";
	import PageWrapper from "@/components/PageWrapper.vue";

	const selectCourse = (ee) => {
		ee.selected = !ee.selected
		console.log('选择的课程列表', selectedCourseIds.value);
	}

	const managerCode = ref(null)

	const manageName = ref(null)
	const studentCourseList = async () => {
		uni.showLoading({
			title: '加载中...'
		})
		try {
			console.log('课程列表请求参数', studentId.value, campusId.value);

			const res = await getStudentCourseList({
				studentId: studentId.value,
				campusId: campusId.value
			});
			if (res.code == 200) {
				if (res.data.length > 0) {
					res.data = res.data.map(course => ({
						...course, // 保留原有的属性
						selected: false // 添加 selected 属性
					}));
				}
				courses.value = res.data
				manageName.value = courses.value[0].jiaoWu
				console.log('课程列表', courses.value);
				uni.hideLoading()
			} else {
				// uni.showToast({
				// 	title: '课程列表请求失败：' + res.message,
				// 	// icon: 'error',
				// 	duration: 2000
				// })
			}
		} catch (error) {
			// console.log('学生课程请求失败', error);
			// uni.showToast({
			// 	title: '课程列表请求失败：' + error.message,
			// 	// icon: 'error',
			// 	duration: 2000
			// })
			uni.hideLoading()
		}
	};
	const toTakePhoto = () => {
		takePhoto.value = false
		uni.navigateTo({
			url: '/pages/takePhoto/takePhoto?campusId=' + campusId.value + '&studentId=' + studentId.value
		});
	};
	const takePhoto = ref(false);
	const showEnterNum = ref(false);
	const showRes = ref(false);


	// 去消课
	const callBackModal = async () => {
		if (managerCode.value) {
			uni.showLoading({
				title: '正在校验学管'
			})
			try {
				// console.log('请求参数', studentId.value, campusId.value);
				const res = await checkManager({
					studentId: studentId.value,
					campusId: campusId.value,
					managerCode: managerCode.value
				});
				if (res.code == 200) {
					// console.log(111, res.data);
					uni.hideLoading()
					managerCode.value = null
					showEnterNum.value = false
					const classes = JSON.stringify(selectedCourseIds.value)
					uni.setStorageSync('courseList', classes)
					console.log('选择的课程', selectedCourseIds.value);
					if (selectedCourseIds.value[0].faceUrl == null) {
						takePhoto.value = true
					} else {
						uni.navigateTo({
							url: '/pages/checkFace/checkFace?campusId=' + campusId.value
						})
					}
				}
			} catch (error) {
				console.log('校验学管请求失败', error);
				uni.showToast({
					title: error.message,
					icon: 'none'
				})
				uni.hideLoading()
			}
		} else {
			uni.showToast({
				title: '工号不能为空',
				icon: 'error'
			})
		}
		// console.log(courses.value);

	};
	let timer = null
	const enterNumber = () => {
		// uni.navigateTo({
		// 	url: '/pages/checkFace/checkFace?campusId=' + campusId.value + '&studentId=' + studentId.value
		// })
		if (selectedCourseIds.value.length > 0) {
			showEnterNum.value = true;
			// 一分钟后自动关闭
			timer = setTimeout(() => {
				hide()
			}, 60000)
		} else {
			uni.showToast({
				title: '请选择课程',
				icon: 'error'
			})
		}
	};
	const hide = () => {
		managerCode.value = null
		showEnterNum.value = false;
		if (timer) clearTimeout(timer)
	}
	const cancel = () => {
		managerCode.value = null
		showEnterNum.value = false;
	}
	const Tipcancel = () => {
		managerCode.value = null
		manageName.value = null
		takePhoto.value = false
	}
	const courses = ref([]);
	// 计算属性：仅存储选中课程的id（核心需求）
	const selectedCourseIds = computed(() => {
		// 过滤选中的课程，提取id组成数组
		return courses.value
			.filter((course) => course.selected) // 只保留选中的课程
			.map((course) => ({
				campusId: campusId.value,
				studentId: studentId.value,
				paiKeMoreId: course.paiKeMoreId,
				tId: course.tId,
				faceUrl: course.faceUrl,
				tName: course.tName,
				subjectName: course.subjectName,
				starTime: course.starTime,
				endTime: course.endTime,
			}));
	});
	// 全选状态
	const allChecked = ref(false);

	// 全选点击事件
	const handleAllClick = () => {
		const newState = !allChecked.value;
		courses.value.forEach((course) => (course.selected = newState));
		allChecked.value = newState;
		console.log('选择的课程列表', selectedCourseIds.value);
	};

	// 课程列表选中状态变化（通过checkbox-group统一监听）
	const handleCourseChange = (e) => {
		// 获取选中的课程索引（与:value对应）
		const selectedIndices = e.detail.value.map(Number);

		// 更新课程选中状态
		courses.value.forEach((course, index) => {
			course.selected = selectedIndices.includes(index);
		});
		console.log(selectedCourseIds.value);
	};

	// 监听课程状态，同步全选框
	watch(
		() => courses.value.every((course) => course.selected),
		(allSelected) => {
			allChecked.value = allSelected;
		}
	);
	// ------------------------------------------------------------------------
	const toIndex = () => {
		uni.navigateTo({
			url: '/pages/index/index'
		});
	}
	const back = () => {
		// uni.navigateTo({
		// 	url: '/pages/index/index'
		// });
		uni.redirectTo({
			url: '/pages/index/index'
		});
	};
	const studentId = ref(null);
	const name = ref(null);
	const campusId = ref(null);
	const faceUrl = ref(null);
	const xiaokeList = ref(null)
	onMounted(() => {})
	onUnmounted(() => {
		if (timer) clearTimeout(timer)
	})
	onLoad((options) => {
		console.log(111, options);
		studentId.value = Number(options.id);
		uni.setStorageSync('studentId', studentId.value)
		campusId.value = options.campusId;
		name.value = options.name;
		faceUrl.value = options.faceUrl;
		console.log('学生录入照片', faceUrl.value);
		console.log(campusId.value);
		if (options.isSuccess) {
			// 显示消课结果列表弹窗
			showRes.value = true
			xiaokeList.value = uni.getStorageSync('xiaokeList')
			console.log(xiaokeList.value);
		}
		// console.log('接收的参数：', options);
		// 4. 处理复杂参数（user：解码+反序列化）
		// if (options.user) {
		// 	// 先解码（decodeURIComponent），再反序列化（JSON.parse）
		// 	user.value = JSON.parse(decodeURIComponent(options.user));
		// }
	});
	onShow(() => {
		uni.$emit('user:interact')
		console.log('课程页面onShow');
		studentCourseList()


	})
</script>

<style scoped>
	.container {
		padding: 20px;
		box-sizing: border-box;
	}

	.item {
		display: flex;
		align-items: center;
		margin-bottom: 12px;
		cursor: pointer;
	}

	checkbox {
		width: 20px;
		height: 20px;
		/* margin-right: 10px; */
		padding-bottom: 20px;
		/* box-sizing: border-box; */
	}

	.label {
		margin-bottom: 18px;
		margin-left: 16px;
		padding-left: 30px;
		padding-right: 30px;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		width: 100%;
		height: 66px;
		font-size: 20px;
		color: #333333;
		min-width: 343px;
		line-height: 22px;
	}

	/* 选中项背景色 */
	.label.checked {
		background-color: #f3f3f3;
	}
</style>